<template>
    <section>
        <el-col :span="24">
            <el-form inline>
                <el-form-item>
                    <el-input v-model.trim="form.combine_sku" size="small" style="width:140px;" placeholder="套装编码" @keyup.enter.native="searchBtn" clearable></el-input>
                </el-form-item>
                <el-form-item>
                    <el-input v-model.trim="form.sku" size="small" style="width:140px;" placeholder="sku" @keyup.enter.native="searchBtn" clearable></el-input>
                </el-form-item>
                <el-form-item>
                    <el-select v-model="form.type" placeholder="渠道" style="width: 100px;" size="small">
                        <el-option v-for="(item, index) in types" :key="index" :label="item.label" :value="item.value"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-date-picker v-model="form.date" type="daterange" unlink-panels range-separator="至" size="small" value-format="yyyy-MM-dd" :clearable="false"
                                    start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="pickerOptions">
                    </el-date-picker>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" class="el-icon-search" @click="searchBtn" size="small" :loading="btnLoading">
                        查询
                    </el-button>
                    <el-button type="text" class="el-icon-upload2" @click="importBtn" size="small" :loading="importLoading" :disabled="!nodeActions.includes('import')">
                        导入
                    </el-button>
                </el-form-item>
            </el-form>
        </el-col>
        <el-col :span="24">
            <el-table :data="data" style="width: 100%" :max-height="tableHeight" v-loading="loading" size="mini">
                <el-table-column type="index" label="序号" width="90"></el-table-column>
                <el-table-column prop="order_date" label="交易日期" width="100"></el-table-column>
                <el-table-column prop="order_number" label="交易号" width="200"></el-table-column>
                <el-table-column prop="combine_sku" label="套装编码" width="130"></el-table-column>
                <el-table-column prop="sku" label="规格编码" width="130"></el-table-column>
                <el-table-column prop="num" label="数量" width="100"></el-table-column>
                <el-table-column prop="createtime" label="导入时间" width="135"></el-table-column>
                <el-table-column></el-table-column>
            </el-table>
            <!--翻页栏-->
            <div style="margin-top: 4px;overflow: hidden;">
                <el-button type="warning" size="small" class="el-icon-s-data" :loading="btnLoading" @click="openSaleBtn" plain>
                    售罄率
                </el-button>
                <Page style="float: right;" :total="total" :current="page" :page-size="limit" show-total @on-change="pageChange"></Page>
            </div>
        </el-col>

        <!--导入-->
        <el-dialog title="导入管理" :visible.sync="importVisible" :close-on-click-modal="false" :close-on-press-escape="false" :before-close="importCloseBtn" width="800px">
            <el-form inline>
                <el-form-item label="选择渠道：">
                    <el-select v-model="uploadData.source" placeholder="渠道" style="width: 100px;" size="small">
                        <el-option v-for="(item, index) in types" :key="index" :label="item.label" :value="item.value"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-upload class="avatar-uploader" action="/api/tool/fileImport" :show-file-list="false" style="margin-bottom: 2px;"
                               :headers="uploadHeaders"
                               :data="uploadData"
                               :on-success="(res)=>uploadSuccessHandle(res)"
                               :before-upload="beforeUploadHandle">
                        <el-button class="el-icon-upload2" type="info" plain size="small" :loading="btnLoading" :disabled="importCache.process<100">上传文件</el-button>
                    </el-upload>
                </el-form-item>
                <el-form-item>
                    <el-button type="text" size="mini" @click="downloadFile('平台销售数据导入模板.xlsx')">
                        <svg style="vertical-align: sub;" t="1720518191914" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5101" width="20" height="20"><path d="M901.851653 926.484607a48.255937 48.255937 0 0 1-14.274541 34.442195 48.844737 48.844737 0 0 1-34.457555 14.279661H170.419644a48.220097 48.220097 0 0 1-34.457555-14.279661 48.844737 48.844737 0 0 1-14.279662-34.442195V48.846068a48.317377 48.317377 0 0 1 14.279662-34.467795A48.844737 48.844737 0 0 1 170.419644 0.001331h418.800096a48.742337 48.742337 0 0 1 34.662355 14.131182l263.858857 263.910057a48.844737 48.844737 0 0 1 14.110701 34.667475z" fill="#EBECF0" p-id="5102"></path><path d="M901.851653 926.484607v48.767936a48.317377 48.317377 0 0 1-14.274541 34.467796 48.844737 48.844737 0 0 1-34.457555 14.279661H170.419644a48.844737 48.844737 0 0 1-48.788417-48.844737v-48.721856a48.204737 48.204737 0 0 0 14.279662 34.442195 48.844737 48.844737 0 0 0 34.457555 14.279661h682.648713a48.844737 48.844737 0 0 0 48.773056-48.783296z" fill="#C1C7D0" p-id="5103"></path><path d="M24.167034 536.423034h975.153932v243.849923a48.921536 48.921536 0 0 1-48.721856 48.844736H73.011771a48.342977 48.342977 0 0 1-34.467796-14.274541 48.844737 48.844737 0 0 1-14.376941-34.570195z" fill="#0AC905" p-id="5104"></path><path d="M121.733627 536.412794V438.856441L24.167034 536.412794z m780.118026 0l0.926719-97.556353 97.039234 97.556353z" fill="#168E2D" p-id="5105"></path><path d="M901.851653 312.628125v6.860791h-263.833257a48.844737 48.844737 0 0 1-48.844736-48.844737V0.001331a48.732097 48.732097 0 0 1 34.662355 14.115822l264.268456 263.751337a49.459136 49.459136 0 0 1 13.701102 34.754515z" fill="#C1C7D0" p-id="5106"></path><path d="M265.190721 764.037458H136.346088v-153.94284h126.335836v35.978193H187.382182v21.749732h63.590317v35.973073h-63.590317v24.268769h77.808539zM358.05716 720.532875l-25.098207 43.504583H276.065587l54.384569-80.322456-49.366976-73.620384h56.893366l21.754852 39.321549 22.589411-39.321549h56.888246L386.508963 683.725242l52.705212 80.317336H382.320809zM599.843726 668.662222h-47.682498q-3.353596-24.268768-27.612124-25.103327-27.612124 0.839679-28.446683 45.178821 0 41.845706 30.120921 41.830345 22.584291 0 25.937886-25.932766h48.522177q-8.376309 59.417523-73.625505 61.91096-78.648218-2.508797-81.151894-79.482777 4.177915-76.124061 76.96886-81.151894 69.43735 0.839679 76.96886 62.750638zM752.112328 764.037458h-128.844633v-153.94284h126.335836v35.978193H674.303789v21.749732h63.590317v35.973073H674.303789v24.268769h77.808539zM897.694219 764.037458H777.215655v-153.94284h51.036094v117.964647h69.44247z" fill="#FFFFFF" p-id="5107"></path></svg>
                        上传模板
                    </el-button>
                </el-form-item>
            </el-form>
            <el-table :data="excelFile" style="width: 100%" height="400px" size="small">
                <el-table-column type="index" width="50" label="#"></el-table-column>
                <el-table-column prop="create_user" label="操作人" width="80"></el-table-column>
                <el-table-column prop="create_time" label="导入时间" width="135"></el-table-column>
                <el-table-column prop="name" label="文件" width="300"></el-table-column>
                <el-table-column prop="status" label="操作">
                    <template slot-scope="scope">
                        <span v-if="scope.row.status == 0 && importCache.process < 100">
                            <el-progress :text-inside="true" :stroke-width="16" status="success" :percentage="importCache.process" :color="importProcessColors"></el-progress>
                        </span>
                        <el-tag v-else size="mini" type="primary">导入完成</el-tag>
                    </template>
                </el-table-column>
            </el-table>
        </el-dialog>

        <!--售罄率-->
        <el-drawer title="售罄率统计" :visible.sync="salesVisible" size="900px" direction="rtl" :wrapperClosable="false">
            <el-row style="padding: 10px;">
                <el-form inline>
                    <el-form-item label="交易日期：">
                        <el-date-picker v-model="salesForm.order_date" type="daterange" unlink-panels range-separator="至" size="small" value-format="yyyy-MM-dd" :clearable="false"
                                        start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="pickerOptions" @change="dateChangeBtn">
                        </el-date-picker>
                    </el-form-item>
                    <el-form-item label="下单日期：">
                        <el-date-picker v-model="salesForm.export_date" type="daterange" unlink-panels range-separator="至" size="small" value-format="yyyy-MM-dd" :clearable="false"
                                        start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="pickerOptions">
                        </el-date-picker>
                    </el-form-item>
                    <el-form-item>
                        <el-select v-model="salesForm.type" placeholder="渠道" style="width: 100px;" size="small">
                            <el-option v-for="(item, index) in types" :key="index" :label="item.label" :value="item.value"></el-option>
                            <el-option label="全部渠道" value="all"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" class="el-icon-s-data" @click="calculateBtn" size="small" :loading="btnLoading">
                            {{btnLoading ? "统计中..." : "开始统计"}}
                        </el-button>
                        <el-button type="text" @click="downloadExcelBtn(salesCacheKey)" size="small" :disabled="!(salesCacheKey&&salesList.length>0)">
                            <svg style="vertical-align: bottom;" t="1726296940186" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="4414" width="16" height="16"><path d="M595.2 755.2h128v88.32L954.88 710.4 723.2 576v89.6h-128zM266.24 134.4c0-6.4 6.4-12.8 12.8-12.8H652.8c3.84 0 7.68 0 12.8 1.28v198.4H864c1.28 5.12 1.28 29.44 1.28 33.28v252.16l49.92 30.72v-281.6c0-34.56-20.48-102.4-43.52-126.72L760.32 117.76C736 93.44 688.64 74.24 654.08 74.24H279.04c-34.56 0-62.72 28.16-62.72 62.72V262.4h49.92v-128z m449.28 10.24c3.84 2.56 6.4 5.12 8.96 7.68l111.36 111.36c2.56 2.56 5.12 5.12 7.68 8.96h-128v-128z" fill="#22975D" p-id="4415"></path><path d="M595.2 385.28H800v58.88H595.2z m270.08 503.04c0 6.4-6.4 12.8-12.8 12.8H279.04c-6.4 0-12.8-6.4-12.8-12.8v-42.24h-49.92v42.24c0 34.56 28.16 62.72 62.72 62.72h574.72c34.56 0 62.72-28.16 62.72-62.72V783.36l-49.92 29.44v75.52zM537.6 320H69.12v468.48H537.6V320zM367.36 687.36l-64-94.72-28.16 43.52h28.16v52.48H160l104.96-153.6L172.8 396.8h76.8l55.04 80.64 55.04-80.64h76.8l-92.16 138.24 104.96 153.6h-81.92z m227.84-185.6H800v58.88H595.2z" fill="#22975D" p-id="4416"></path></svg>
                            导出Excel
                        </el-button>
                    </el-form-item>
                </el-form>
                <el-table :data="salesList.filter(data => !sku || data.sku.toLowerCase().includes(sku.toLowerCase()))"
                          style="width: 100%" :max-height="tableHeight+15" v-loading="loading" size="mini">
                    <el-table-column type="index" label="序号" width="90"></el-table-column>
                    <el-table-column prop="sku" label="规格编码" width="130"></el-table-column>
                    <el-table-column prop="sale_num" label="销售数量" width="130" sortable></el-table-column>
                    <el-table-column prop="num" label="下单数量" width="130" sortable></el-table-column>
                    <el-table-column prop="rate" label="售罄率(%)" width="130" sortable></el-table-column>
                    <el-table-column align="right">
                        <template slot="header" slot-scope="scope">
                            <el-input v-model="sku" size="mini" placeholder="输入sku搜索" clearable></el-input>
                        </template>
                    </el-table-column>
                </el-table>
            </el-row>
        </el-drawer>
    </section>
</template>

<script>

import {formatDate} from "../../libs/tools";
import {getToken} from "../../libs/util";
import {salesExcelList, salesImportCache, salesList, salesSRate} from "../../api/om/sales";

export default {
    name: "om_sales",
    data() {
        return {
            tableHeight: window.innerHeight - 210,
            selectIndex: 0,
            btnLoading: false,
            loading: false,
            page: 1,
            limit: 20,
            total: 0,
            data: [],
            user: {},
            nodeActions: [],

            types: [
                {label: '淘系', value: 'top'},
                {label: '抖音', value: 'douyin'}
            ],
            form: {combine_sku: "", sku: "", type: "top", date: [formatDate(new Date().getTime()-3600 * 1000 * 24 * 7, "date"), formatDate(new Date().getTime(), "date")]},
            pickerOptions: {
                shortcuts: [
                    {
                        text: '昨天',
                        onClick(picker) {
                            const start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 1);
                            picker.$emit('pick', [start, start]);
                        }
                    },{
                        text: '今天',
                        onClick(picker) {
                            const start = new Date();
                            picker.$emit('pick', [start, start]);
                        }
                    },{
                        text: '近7天',
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                            picker.$emit('pick', [start, end]);
                        }
                    }, {
                        text: '当月',
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(new Date(formatDate(new Date().getTime(), 'month_first_day')));
                            picker.$emit('pick', [start, end]);
                        }
                    }, {
                        text: '上月',
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(new Date(formatDate(new Date().getTime(), 'last_month_first_day')));
                            end.setTime(new Date(formatDate(new Date().getTime(), 'last_month_last_day')))
                            picker.$emit('pick', [start, end]);
                        }
                    }, {
                        text: '今年',
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(new Date(formatDate(new Date().getTime(), 'year')+"-01-01"));
                            picker.$emit('pick', [start, end]);
                        }
                    }, {
                        text: '去年',
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(new Date(formatDate(new Date().getTime(), 'last_year')+"-01-01"));
                            end.setTime(new Date(formatDate(new Date().getTime(), 'last_year')+"-12-31"));
                            picker.$emit('pick', [start, end]);
                        }
                    }
                ]
            },

            importProcessColors:[
                {color: '#1989fa', percentage: 50},
                {color: '#2994CA', percentage: 60},
                {color: '#38A1AB', percentage: 70},
                {color: '#48AB8D', percentage: 80},
                {color: '#57B76E', percentage: 90},
                {color: '#67C23A', percentage: 95},
                {color: '#67C23A', percentage: 100}
            ],
            importLoading: false,
            importVisible:false,
            importTimeout: null,
            excelFile: [],
            importCache: {},

            uploadHeaders: {},
            uploadData:{type: 'oms_sales', disk: 'excel', source: 'top'},

            salesVisible: false,
            salesForm: {
                type: "top",
                order_date: [formatDate(new Date().getTime()-3600 * 1000 * 24 * 7, "date"), formatDate(new Date().getTime(), "date")],
                export_date: [(new Date().getFullYear())+"-01-01", formatDate(new Date().getTime(), "date")]
            },
            salesList: [],
            salesCacheKey: "",

            sku: "",
        }
    },
    created() {
        this.user = this.$store.getters.user;
        this.nodeActions = this.user.node_actions[this.$route.meta.id] ? this.user.node_actions[this.$route.meta.id] : [];
    },
    methods: {
        //搜索按钮
        searchBtn() {
            this.page = 1;
            this.getData();
        },
        //翻页
        pageChange(page) {
            this.page = page;
            this.getData();
        },
        //获取数据
        getData() {
            let param = {
                page: this.page,
                limit: this.limit
            };
            param = Object.assign(param, this.form);
            this.loading = true;
            this.btnLoading = true;
            salesList(param).then((res) => {
                this.loading = false;
                this.btnLoading = false;
                this.total = res.data.total;
                this.data = res.data.data;
            }).catch(() => {
                this.loading = false;
                this.btnLoading = false;
            });
        },

        //下载
        downloadFile(name){
            window.open('/api/tool/fileExport'+`?path=template&type=file&name=${name}`, '_self');
        },

        importCloseBtn(){
            clearTimeout(this.importTimeout);
            this.importTimeout = null;
            this.importVisible = false;
        },
        importBtn(){
            this.importLoading = true;
            salesExcelList().then((res) =>{
                this.importLoading = false;
                this.excelFile = res.data.data;
                this.importCache = res.data.cache;
                this.importVisible = true;
                if(this.importCache.file && this.importCache.process<100){
                    this.loopImportCache();
                }
            }).catch(()=>{
                this.importLoading = false;
            })
        },
        loopImportCache(){
            let that = this;
            salesImportCache().then((res) =>{
                if(res.data.file && res.data.process<100){
                    this.importCache = res.data;
                    this.importTimeout = setTimeout(function (){
                        that.loopImportCache();
                    },2000)
                }else{
                    this.importCache = {};
                    this.importBtn();
                }
            })
        },
        //上传之前的检测
        beforeUploadHandle(file) {
            if(!/\.xls(x?)$/.test(file.name)){
                this.$message.warning('上传文件格式：请修改成xlsx、xls!');
                return false;
            }
            this.uploadHeaders.Authorization = 'Bearer '+ getToken();
            this.btnLoading = true;
            return true;
        },
        //上传成功
        uploadSuccessHandle(res) {
            this.btnLoading = false;
            if(res.code === 0){
                this.$message.success("文件已上传，请耐心等待数据写入...");
                this.excelFile.unshift(res.data.data);
                this.importCache = res.data.cache;
                if(this.importCache.file && this.importCache.process<100){
                    this.loopImportCache();
                }
            }else{
                this.$message.error(res.msg);
            }
        },

        dateChangeBtn(val){
            this.$set(this.salesForm.export_date, 1, val[1]);
        },
        //打开售罄率
        openSaleBtn(){
            this.salesVisible = true;
        },
        //开始计算
        calculateBtn(){
            this.btnLoading = true;
            salesSRate(this.salesForm).then((res) => {
                this.btnLoading = false;
                this.salesList = res.data.data;
                this.salesCacheKey = res.data.cache_key;
            }).catch(() => {
                this.btnLoading = false;
            })
        },
        //导出excel
        downloadExcelBtn(id){
            this.$confirm("导出excel, 是否继续？", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            }).then(() => {
                window.open(`/api/tool/fileExport?type=excel&name=售罄率&path=${id}`, "_self");
            }).catch(() => {

            })
        },
    },
    mounted() {
        this.searchBtn();
    }
}
</script>

<style scoped>

</style>
